package com.chencai.wiki;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.http.*;

@SuppressWarnings("serial")
public class PersonelWikiServlet extends HttpServlet
{
	

	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException 
	{
		
		Map<String, String> params = parseQueryString(req.getQueryString());
		String method = params.get("methodID");
		String responseString = WikiBussiness.processRequest(params, method);
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("utf-8");
		resp.getWriter().println(responseString);

		
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException 
	{
		String result = inputStreamToString(req.getInputStream());
		//System.out.println(result);
		Map<String, String> params = parseQueryString(result);
		String method = params.get("methodID");
		String responseString = WikiBussiness.processRequest(params, method);
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("utf-8");
		resp.getWriter().println(responseString);

		
	}
	
	private Map<String, String> parseQueryString(String queryString) throws IOException
	{
		Map<String, String> ret = new HashMap<String, String>();
		String[] params = queryString.trim().split("&");
		String[] pair;
		for(String param : params){
			pair = param.trim().split("=");
			pair[0] = URLDecoder.decode(pair[0], "utf-8").trim();
			pair[1] = URLDecoder.decode(pair[1], "utf-8").trim();
			//System.out.println( pair[0] + ":" + pair[1] );
			ret.put(pair[0], pair[1]);
		}
		return ret;			
	}
	
    private String inputStreamToString(final InputStream inputStream) throws IOException {
    	final StringBuilder outputBuilder = new StringBuilder();
    	
    	try {
    		String string;
    		if (inputStream != null) {
    			BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
    			while (null != (string = reader.readLine())) {
    				outputBuilder.append(string).append('\n');
    			}
    		}
    	} catch (Exception ex) {
    		throw new IOException("read input stream error", ex);
    	}
    	
    	return outputBuilder.toString();
    }
	
	
	
}
